package com.dcdata.jt809server.thread;

import com.dcdata.jt809server.bean.dto.TrafficVehicleLocationDTO;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Date;


/**
 * program: JT809Server
 * description:
 * @author DCDATA
 * @date 2020-10-23 20:43
 **/
@Slf4j
public class VehicleLocationThread implements Runnable {

    private final TrafficVehicleLocationDTO trafficVehicleLocationDTO;

    public VehicleLocationThread(TrafficVehicleLocationDTO trafficVehicleLocationDTO) {
        this.trafficVehicleLocationDTO = trafficVehicleLocationDTO;
    }

    @Override
    public void run() {
        log.info("车辆定位信息持久化线程启动，内容为：{}", trafficVehicleLocationDTO);
        // 寫文件
        try {
            this.writeLocalGPS(trafficVehicleLocationDTO.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("writeHDFSGPS存在错误！！" + new Date());
        }
        log.info("车辆定位信息持久化线程执行结束。");
    }

    private synchronized void writeLocalGPS(String response) {
        LocalDate localDate = LocalDate.now();
        String fileName = System.getProperty("user.dir") + "/data/GPS"+localDate.toString().replace("-","_")+".txt";

        File dataDir = new File(System.getProperty("user.dir") + "/data");
        if  (!dataDir .exists()  && !dataDir .isDirectory())
            if(!dataDir.mkdir()){
                log.info("mkdir data failed");
            }


        File file = new File(fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file,true);
            byte[] bytes = (response+"\n").getBytes();
            for (byte aByte : bytes) {
                fos.write(aByte);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                assert fos != null;
                fos.flush(); //强制刷新输出流
                fos.close(); //强制关闭输出流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
